package com.example.weight.householdWaste;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.model.FaultModel;
import com.example.weight.navigation.HouseholdWasteNavActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class FaultRepairAfterActivity extends AppCompatActivity {

    private String id, system, equipment, step, occurTime, description, personInCharge, factory;

    private EditText systemName, facilityName, stepText,
            occurTimeText, faultDescription, occurReason,
            repairMethod, provider, repairDate, repairStartTime,
            repairEndDate, repairEndTime, repairPerson, personInChargeText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fault_repair_after);

        Intent previousIntent = getIntent();
        id = previousIntent.getStringExtra("id");
        system = previousIntent.getStringExtra("system");
        equipment = previousIntent.getStringExtra("equipment");
        step = previousIntent.getStringExtra("step");
        occurTime = previousIntent.getStringExtra("occurTime");
        description = previousIntent.getStringExtra("description");
        personInCharge = previousIntent.getStringExtra("personInCharge");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.fault_repair_after_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        systemName = findViewById(R.id.fault_repair_after_system_name);
        facilityName = findViewById(R.id.fault_repair_after_facility_name);
        stepText = findViewById(R.id.fault_repair_after_step);
        occurTimeText = findViewById(R.id.fault_repair_after_fault_occur_time);
        faultDescription = findViewById(R.id.fault_repair_after_fault_situation);
        occurReason = findViewById(R.id.fault_repair_after_fault_reason);
        repairMethod = findViewById(R.id.fault_repair_after_fault_repair_method);
        provider = findViewById(R.id.fault_repair_after_fault_repair_method_person);
        repairDate = findViewById(R.id.fault_repair_after_fault_repair_date);
        repairStartTime = findViewById(R.id.fault_repair_after_fault_repair_start_time);
        repairEndDate = findViewById(R.id.fault_repair_after_repair_end_date);
        repairEndTime = findViewById(R.id.fault_repair_after_fault_repair_end_time);
        repairPerson = findViewById(R.id.fault_repair_after_fault_repair_person);
        personInChargeText = findViewById(R.id.fault_repair_after_personInCharge);

        systemName.setText(system);
        facilityName.setText(equipment);
        stepText.setText(step);
        occurTimeText.setText(occurTime);
        faultDescription.setText(description);
        personInChargeText.setText(personInCharge);

        repairDate.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                final int YEAR = calendar.get(Calendar.YEAR);
                final int MONTH = calendar.get(Calendar.MONTH);
                final int DAY = calendar.get(Calendar.DAY_OF_MONTH);

                @SuppressLint({"SetTextI18n", "ResourceType"})
                DatePickerDialog datePickerDialog = new DatePickerDialog(FaultRepairAfterActivity.this, 2,
                        (view1, year, month, day) ->
                                repairDate.setText(year + "/"
                                        + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) + "/"
                                        + ((day < 10) ? "0" + day : day)),
                        YEAR,
                        MONTH,
                        DAY);
                datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        repairDate.clearFocus();
                    }
                });
                datePickerDialog.show();
            }
        });
        repairStartTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"DefaultLocale", "SetTextI18n"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(FaultRepairAfterActivity.this, 2,
                        (view1, hourOfDay, minute) ->
                                repairStartTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        repairStartTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });
        repairEndDate.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                final int YEAR = calendar.get(Calendar.YEAR);
                final int MONTH = calendar.get(Calendar.MONTH);
                final int DAY = calendar.get(Calendar.DAY_OF_MONTH);

                @SuppressLint({"SetTextI18n", "ResourceType"})
                DatePickerDialog datePickerDialog = new DatePickerDialog(FaultRepairAfterActivity.this, 2,
                        (view1, year, month, day) ->
                                repairEndDate.setText(year + "/"
                                        + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) + "/"
                                        + ((day < 10) ? "0" + day : day)),
                        YEAR,
                        MONTH,
                        DAY);
                datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        repairEndDate.clearFocus();
                    }
                });
                datePickerDialog.show();
            }
        });
        repairEndTime.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Calendar calendar = Calendar.getInstance();
                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
                int MINUTE = calendar.get(Calendar.MINUTE);

                @SuppressLint({"DefaultLocale", "SetTextI18n"})
                TimePickerDialog timePickerDialog = new TimePickerDialog(FaultRepairAfterActivity.this, 2,
                        (view1, hourOfDay, minute) ->
                                repairEndTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                        ,HOUR
                        ,MINUTE
                        ,true);
                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
                    if (which == DialogInterface.BUTTON_NEGATIVE) {
                        //取消操作
                        repairEndTime.clearFocus();
                    }
                });
                timePickerDialog.show();
            }
        });
    }

    @SuppressLint({"SetTextI18n", "ResourceType"})
    public void selectRepairDate(View view) {
        Calendar calendar = Calendar.getInstance();
        final int YEAR = calendar.get(Calendar.YEAR);
        final int MONTH = calendar.get(Calendar.MONTH);
        final int DAY = calendar.get(Calendar.DAY_OF_MONTH);

        new DatePickerDialog(this, 2, (view1, year, month, day) ->
                repairDate.setText(year + "/"
                        + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) + "/"
                        + ((day < 10) ? "0" + day : day)),
                YEAR,
                MONTH,
                DAY).show();
    }

    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    public void selectRepairStartTime(View view) {
        Calendar calendar = Calendar.getInstance();
        final int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        final int MINUTE = calendar.get(Calendar.MINUTE);

        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                repairStartTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }

    @SuppressLint({"SetTextI18n", "ResourceType"})
    public void selectRepairEndDate(View view) {
        Calendar calendar = Calendar.getInstance();
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);

        new DatePickerDialog(this, 2, (view1, year, month, day) ->
                repairDate.setText(year + "/"
                        + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) + "/"
                        + ((day < 10) ? "0" + day : day)),
                YEAR,
                MONTH,
                DAY).show();
    }

    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    public void selectRepairEndTime(View view) {
        Calendar calendar = Calendar.getInstance();
        final int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        final int MINUTE = calendar.get(Calendar.MINUTE);

        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
                repairEndTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
                ,HOUR
                ,MINUTE
                ,true).show();
    }

    public void save(View view) {
        if (occurReason.getText().toString().equals("")) {
            Toast.makeText(this, "请填写故障发生原因", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repairMethod.getText().toString().equals("")) {
            Toast.makeText(this, "请填写维修方法", Toast.LENGTH_SHORT).show();
            return;
        }
        if (provider.getText().toString().equals("")) {
            Toast.makeText(this, "请填写方法提出人", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repairDate.getText().toString().equals("")) {
            Toast.makeText(this, "请填写修理开始日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repairStartTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写修理开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repairEndDate.getText().toString().equals("")) {
            Toast.makeText(this, "请填写修理结束日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repairEndTime.getText().toString().equals("")) {
            Toast.makeText(this, "请填写修理结束时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repairPerson.getText().toString().equals("")) {
            Toast.makeText(this, "请填写维修人员", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String addUrl = Config.url + "/shlj/troubleshooting/addAfterPart";
                    StringRequest addRequest = new StringRequest(Request.Method.POST, addUrl,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
//                                    systemName.setText("");
//                                    facilityName.setText("");
//                                    step.setText("");
//                                    occurDate.setText("");
//                                    occurTime.setText("");
//                                    faultDescription.setText("");
//                                    occurReason.setText("");
//                                    repairMethod.setText("");
//                                    provider.setText("");
//                                    repairDate.setText("");
//                                    repairStartTime.setText("");
//                                    repairEndTime.setText("");
//                                    repairPerson.setText("");
//                                    personInCharge.setText("");

                                        if (code.startsWith("2"))
                                            Toast.makeText(FaultRepairAfterActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(FaultRepairAfterActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();

                                        String getListUrl = Config.url + "/shlj/troubleshooting/getList" + "?factory=" + factory;
                                        StringRequest getListRequest = new StringRequest(Request.Method.GET, getListUrl,
                                                new Response.Listener<String>() {
                                                    public void onResponse(String response) {
                                                        try {
                                                            JSONObject jsonObject = new JSONObject(response);
                                                            if (!jsonObject.isNull("data")) {
                                                                String listString = "";
                                                                JSONArray data = jsonObject.getJSONArray("data");
                                                                for (int i = 0; i < data.length(); i++) {
                                                                    JSONObject item = data.getJSONObject(i);
                                                                    String id = item.getString("id");
                                                                    String system = item.getString("systemName");
                                                                    String equipment = item.getString("equipmentName");
                                                                    String occurTime = item.getString("timeOfFailure");
                                                                    String step = item.getString("stage");
                                                                    String description = item.getString("faultDescription");
                                                                    String personInCharge = item.getString("personInCharge");
                                                                    FaultModel faultModel = new FaultModel(id, system, equipment, occurTime, step, description, personInCharge);
                                                                    listString = listString.concat(faultModel.toSplitWithSpace());
                                                                    if (i < data.length()-1)
                                                                        listString = listString.concat(",");
                                                                }

                                                                Intent intent = new Intent();
                                                                intent.putExtra("list", listString);
                                                                intent.putExtra("needRefresh", true);
                                                                intent.putExtra("factory", factory);
                                                                setResult(RESULT_OK, intent);

                                                                finish();
                                                            }
                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                }, new Response.ErrorListener() {
                                            @Override
                                            public void onErrorResponse(VolleyError error) {}
                                        });
                                        getListRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                                        queue.add(getListRequest);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(FaultRepairAfterActivity.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", id);
                            map.put("faultReasion", occurReason.getText().toString());
                            map.put("faultRepairMethod", repairMethod.getText().toString());
                            map.put("repairStartTime", repairDate.getText().toString()+" "+repairStartTime.getText().toString());
                            map.put("repairEndTime", repairEndDate.getText().toString()+" "+repairEndTime.getText().toString());
                            map.put("repairPerson", repairPerson.getText().toString());
                            map.put("methodProposer", provider.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    addRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(addRequest);
                })
                .show();
    }
}